const fs = require('fs');
const path = require('path');
const sharp = require('sharp');
const { promisify } = require('util');
const fsPromises = fs.promises;
const rename = promisify(fs.rename);

// 指定要压缩的目录
const directoryPath = path.join(__dirname, '../resources/img/style');
// const directoryPath = path.join(__dirname, '../resources/img');
// 控制并发数
const concurrencyLimit = 5;

(async () => {
  try {
    await processDirectory(directoryPath);
  } catch (err) {
    console.error(err);
  }
})();

async function processDirectory(dirPath) {
  const entries = await fsPromises.readdir(dirPath, { withFileTypes: true });

  for (const entry of entries) {
    const fullPath = path.join(dirPath, entry.name);

    if (entry.isDirectory()) {
      await processDirectory(fullPath);
    } else if (entry.isFile() && path.extname(entry.name) === '.jpg') {
      const tempFilePath = `${fullPath}.tmp`;
      
      await processFile(fullPath, tempFilePath);
    }
  }
}

async function processFile(oldFilePath, newFilePath) {
  try {
    await sharp(oldFilePath)
      .jpeg({ quality: 50 }) // 调整质量以实现压缩，50为质量百分比，可以根据需要调整
      .toFile(newFilePath);

    await rename(newFilePath, oldFilePath);
    console.log(`Compressed and replaced: ${oldFilePath}`);
  } catch (err) {
    console.error(`Failed to process file ${oldFilePath}:`, err);
  }
}